<?php namespace App\Http\Controllers\Api;

use App\CoinLog;
use App\Files;
use App\Goods;
use App\GoodsAttr;
use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Http\Services\Tools;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\Orders;
use App\User;
use App\UserInfo;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;

class GoodsController extends Controller
{
    public function buildOrder(Guard $guard,Request $request){
        $gid      = $request->get('gid');
        $attrId   = $request->get('attr_id');
        $num      = $request->get('num');
        $realname = $request->get('realname');
        $phone    = $request->get('phone');
        $qq       = $request->get('qq');
        $wechat   = $request->get('wechat');
        $address  = $request->get('address');
        $wxPhotoId= $request->get('picture_id');

        if($guard->guest())
            return response()->json(['level'=>'error','message'=>'请先登录']);
        /** @var User $user */
        $user = $guard->user();

        $userinfo = UserInfo::whereUserId($user->id)->first();

        if(!$userinfo)
            return response()->json(['level'=>'error','message'=>'用户信息错误']);

        /** @var Goods $thatGood */
        $thatGood = Goods::whereId($gid)->first();
        if(!$thatGood)
            return response()->json(['level'=>'error','message'=>'该商品不存在']);

        $thatGoodAttr = null;
        if($attrId != 0 || !is_null($attrId) || $attrId != ''){
            /** @var GoodsAttr $thatGoodAttr */
            $thatGoodAttr = GoodsAttr::whereGoodId($thatGood->id)->whereId($attrId)->first();
            if(!$thatGoodAttr)
                return response()->json(['level'=>'error','message'=>'该商品属性不存在']);
        }

        $coin = 0;
        if($thatGood->type != 2){
            $coin = (int)$thatGood->coin * (int)$num;
            if((int)$userinfo->coin < (int)$coin){
                return response()->json(['level'=>'error','message'=>'波罗币不足','data'=>(int)$userinfo->coin]);
            }
        }

        $amount = 0;
        if($thatGood->type == 2){
            if($num > $thatGood->stock){
                $num = $thatGood->stock;
            }

            $eAmount = 8;
            if($num >= 5){
                $eAmount = 0;
            }

            $amount = (float)$thatGood->amount * (int)$num + $eAmount;
        }

        $order = new Orders();
        $order->good_id = $thatGood->id;
        $order->user_id = $user->id;
        $order->order_num = Tools::makeBillNum();
        $order->num       = $num;
        $order->attr_name = $thatGoodAttr ? $thatGoodAttr->name : '';
        $order->coin      = $coin;
        if($thatGood->type == 1){
            $order->pay_type  = 'buluobi';
        }else{
            $order->pay_type  = 'wxpay';
        }
        if($thatGood->type == 2)$order->amount    = $amount;
        $order->realname  = $realname;
        $order->phone     = $phone;
        $order->qq        = $qq;
        $order->wechat    = $wechat;
        $order->address   = $address;

        $accessToken = WechatLogin::getWechatAccessTokenBySecret();

        $headImgUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$accessToken->getAccessToken()."&media_id=".$wxPhotoId;

        /** @var Files $fileModel */
        $fileModel = FileManager::saveFileByWechatHeaderImg($headImgUrl,$wxPhotoId);
        if($fileModel){
            $imageModel = Images::whereFileId($fileModel->id)->first();
            if(!$imageModel){
                $imageModel = new Images();
                $imageModel->file_id = $fileModel->id;
                $imageModel->img_name= 'wechat_img';
                $imageModel->img_type= $fileModel->file_type;
                $imageModel->save();

                $order->picture_id = $imageModel->id;
            }
        }
        $order->save();

        return response()->json(['level'=>'success','message'=>'提交订单成功，请等待客服人员联系','data'=>$order]);
    }

    public function confirmOrder(Guard $guard,Request $request){
        $orderId = $request->get('order_id');

        if($guard->guest())
            return response()->json(['level'=>'error','message'=>'请先登录']);
        /** @var User $user */
        $user = $guard->user();

        $userinfo = UserInfo::whereUserId($user->id)->first();

        if(!$userinfo)
            return response()->json(['level'=>'error','message'=>'用户信息错误']);

        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereId($orderId)->whereUserId($user->id)->first();

        if(!$thatOrder)
            return response()->json(['level'=>'error','message'=>'当前订单不存在']);

        $thatOrder->is_pay = 1;
        $thatOrder->pay_time  = date('Y-m-d H:i:s',time());
        $thatOrder->status = 1;
        $thatOrder->save();

        $userinfo->coin = (int)$userinfo->coin - (int)$thatOrder->coin;
        $userinfo->save();

        $coinLog = new CoinLog();
        $coinLog->user_id = $user->id;
        $coinLog->coin    = -(int)$thatOrder->coin;
        $coinLog->desc    = '购买消费';
        $coinLog->save();

        return response()->json(['level'=>'success','message'=>'提交订单成功']);
    }
}